<template>
  <!-- 规格弹窗 -->
  <su-popup :show="authType !== ''" round="10" :showClose="true" @close="closeAuthModal">
    <view class="login-wrap">
      <view class="login-title">登录</view>
      <!-- 7. 第三方登录 -->
      <view
        v-if="['accountLogin', 'smsLogin'].includes(authType)"
        class="auto-login-box ss-flex ss-flex-col ss-row-center ss-col-center"
      >
        <!-- 7.1 支付宝手机号快捷登录 -->
        <view v-if="sheep.$platform.name === 'AlipayMiniProgram'" class="login-box">
          <button
            class="login-btn"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
          >
            使用手机号快捷登录
          </button>
          <!--          <button-->
          <!--            class="login-btn"-->
          <!--            @tap="getMyPhoneNumber()"-->
          <!--          >-->
          <!--            my.getPhoneNumber-->
          <!--          </button>-->
          <!--          <button-->
          <!--            class="login-btn"-->
          <!--            @tap="getAuthCode()"-->
          <!--          >-->
          <!--            授权按钮-->
          <!--          </button>-->
        </view>
        <view v-if="sheep.$platform.name === 'AlipayMiniProgram'" class="login-box">
        </view>
      </view>

      <!-- 用户协议的勾选 -->
      <view
        v-if="sheep.$platform.name === 'AlipayMiniProgram'"
        class="agreement-box ss-flex ss-row-center"
        :class="{ shake: currentProtocol }"
      >
        <label class="radio ss-flex ss-col-center" @tap="onChange">
          <radio
            :checked="state.protocol"
            color="var(--ui-BG-Main)"
            style="transform: scale(0.8)"
            @tap.stop="onChange"
          />
          <view class="agreement-text ss-flex ss-col-center ss-m-l-8">
            我已阅读并遵守
            <view class="tcp-text" @tap.stop="onProtocol('用户协议')">
              《用户协议》
            </view>
            <view class="agreement-text">与</view>
            <view class="tcp-text" @tap.stop="onProtocol('隐私协议')">
              《隐私协议》
            </view>
          </view>
        </label>
      </view>
      <view class="safe-box"/>
    </view>
  </su-popup>
</template>

<script setup>
  import { computed, reactive, ref } from 'vue';
  import sheep from '@/sheep';
  import accountLogin from './components/account-login.vue';
  import smsLogin from './components/sms-login.vue';
  import resetPassword from './components/reset-password.vue';
  import changeMobile from './components/change-mobile.vue';
  import changePassword from './components/change-password.vue';
  import mpAuthorization from './components/mp-authorization.vue';
  import alipayAuthorization from './components/alipay-authorization.vue';
  import { closeAuthModal, showAuthModal } from '@/sheep/hooks/useModal';
  import AuthUtil from '@/sheep/api/member/auth';

  const appInfo = computed(() => sheep.$store('app').info);

  const modalStore = sheep.$store('modal');
  console.log(modalStore)
  console.log(modalStore.auth)
  console.log(sheep.$platform.name)
  // 授权弹窗类型
  const authType = computed(() => modalStore.auth);
  console.log(authType)
  const state = reactive({
    protocol: false,
  });

  const currentProtocol = ref(false);

  // 勾选协议
  function onChange() {
    state.protocol = !state.protocol;
  }

  // 查看协议
  function onProtocol(title) {
    closeAuthModal();
    sheep.$router.go('/pages/public/richtext', {
      title,
    });
  }

  // 点击登录 / 注册事件
  function onConfirm(e) {
    currentProtocol.value = e;
    setTimeout(() => {
      currentProtocol.value = false;
    }, 1000);
  }

  // 第三方授权登陆（微信小程序、Apple）
  const thirdLogin = async (provider) => {
    if (!state.protocol) {
      currentProtocol.value = true;
      setTimeout(() => {
        currentProtocol.value = false;
      }, 1000);
      sheep.$helper.toast('请勾选同意');
      return;
    }
    const loginRes = await sheep.$platform.useProvider(provider).login();
    if (loginRes) {
      closeAuthModal();
      // 触发小程序授权信息弹框
      // #ifdef MP-WEIXIN
      showAuthModal('mpAuthorization');
      // #endif
    }
  };

  // 手机号快捷登录
  const getPhoneNumber = async (e) => {
    if (e.detail.errMsg !== 'getPhoneNumber:ok') {
      sheep.$helper.toast('快捷登录失败');
      return;
    }
    my.getPhoneNumber({
      scopes: 'auth_base',
      success: async (res) => {
        console.log('这里是my.getPhoneNumber的结果：',res)
        let encryptedData = res.response;
        const openId = uni.getStorageSync('openid');
        const authCode = uni.getStorageSync('authCode');
        console.log(openId)
        const params = {
          phoneCode: encryptedData,
          loginCode: authCode,
          openId: openId,
          state: 'default'
        }
        console.log(params)
        const {code, bulData} = await AuthUtil.alipayBindPhoneNumberLogin(params)

        if (code===0) {
          closeAuthModal();
        }
      },
      fail: err => {
        console.log('my.getPhoneNumber 调用失败', err)
      }
    });
  };
  // 支付宝快捷登录
  const getMyPhoneNumber = async () => {
    if (sheep.$platform.name === 'AlipayMiniProgram') {
      my.getPhoneNumber({
        scopes: 'auth_base',
        success: async (res) => {
          console.log('这里是my.getPhoneNumber的结果：',res)
          let encryptedData = res.response;
          let result = await AuthUtil.alipayUnsensibleLogin(encryptedData);
          console.log('调用服务器接口结果：', result)
        },
        fail: err => {
          console.log('my.getPhoneNumber 调用失败', err)
        }
      });
    }
  }
  const getAuthCode = async () => {
    if (sheep.$platform.name === 'AlipayMiniProgram') {
      my.getAuthCode({
        scopes: 'auth_base',
        success: async (res) => {
          console.log('这里是getAuthCode的结果：',res)
          const authCode = res.authCode;
          // 先通过静默登录，获取登录情况，并获取openid
          const {code, data} = await AuthUtil.alipayUnsensibleLogin(authCode);
          if(code === 0){
            console.log('调用服务器接口结果：', data)
            // 判断登录
            console.log('isLogin', sheep.$store('user').isLogin)
            if(sheep.$store('user').isLogin){

            } else {
              uni.setStorageSync('openid', data.openid);
              my.getPhoneNumber({
                scopes: 'auth_base',
                success: async (res) => {
                  console.log('这里是my.getPhoneNumber的结果：',res)
                  let encryptedData = res.response;
                  const params = {
                    phoneCode: encryptedData,
                    loginCode: authCode,
                    openId: data.openid
                  }
                  const {code, bulData} = await AuthUtil.alipayBindPhoneNumberLogin(params)
                },
                fail: err => {
                  console.log('my.getPhoneNumber 调用失败', err)
                }
              });

            }
          }
        },
        fail: err => {
          console.log('my.getAuthCode 调用失败', err)
        }
      });
    }
  };
</script>

<style lang="scss" scoped>
  @import './index.scss';

  .shake {
    animation: shake 0.05s linear 4 alternate;
  }

  @keyframes shake {
    from {
      transform: translateX(-10rpx);
    }
    to {
      transform: translateX(10rpx);
    }
  }
  .login-wrap {
    padding-top: 0;
  }
  .login-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
    text-align: center;
    margin-bottom: 64rpx;
  }
  .login-box {
    padding: 32rpx;
    width: 100%;
    .login-btn {
      background: #0081ff;
      color: #fff;
      font-size: 30rpx;
      border-radius: 32rpx;
    }
  }
  .safe-box {
    height: calc(constant(safe-area-inset-bottom) / 5 * 3);
    height: calc(env(safe-area-inset-bottom) / 5 * 3);
  }

  .tcp-text {
    color: var(--ui-BG-Main);
  }

  .agreement-box {
    margin: 0;
  }

  .agreement-text {
    color: $dark-9;
  }
</style>
